package com.alawn.framework.services.security;

import com.alawn.framework.core.domain.AuditableEntity;
import com.alawn.framework.core.utils.Digests;
import com.alawn.framework.core.utils.Encodes;
import com.alawn.framework.services.enums.UserStatus;
import com.alawn.framework.services.enums.UserType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Getter;
import lombok.Setter;

import java.time.LocalDate;

/**
 * <p>
 * 账号表
 * </p>
 *
 * @author johnny
 * @since 2019-02-27
 */
@Getter
@Setter
@TableName("mz_a_user")
public class User extends AuditableEntity {

	private static final long serialVersionUID = 1L;

	/**
	 * 用户类型：0USER、1ADMIN
	 */
	private UserType type;

	/**
	 * 用户名
	 */
	private String username;

	/**
	 * 密码
	 */
	private String password;

	/**
	 * 二次密码
	 */
	@TableField(exist = false)
	private String plainPassword;

	/**
	 * 加密盐
	 */
	private String salt;

	/**
	 * 支付宝用户登入ID
	 */
	private String alipayUseId;

	/**
	 * 新浪微博用户登入的ID
	 */
	private String sinaWeiboId;

	/**
	 * 腾讯微信用户登入ID
	 */
	private String tencentWechatId;

	/**
	 * 主题偏好ID
	 */
	private Long preferenceId;

	/**
	 * 移动电话
	 */
	private String mobile;

	/**
	 * 邮箱
	 */
	private String email;

	/**
	 * 账号状态：unactivated账户未激活，freeze冻结（超出尝试登入次数），locked锁定登入次数过多
	 */
	private UserStatus status;

	/**
	 * 冻结日期
	 */
	private LocalDate freezeDate;

	/**
	 * 最后一次登入ip地址
	 */
	private String ipAddr;

	/**
	 * 最后一次登入主机地址
	 */
	private String macAddr;

	public void setPlainPassword(String plainPassword) {
		byte[] salt = Digests.generateSalt(Digests.SALT_SIZE);
		this.setSalt(Encodes.encodeHex(salt));
		this.setPassword(entryptPassword(plainPassword, salt));
		this.plainPassword = plainPassword;
	}

	public byte[] getCredentialsSalt() {
		return Encodes.decodeHex(getSalt());
	}

	private String entryptPassword(String plainPassword, byte[] salt) {
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, Digests.HASH_INTERATIONS);
		String password = Encodes.encodeHex(hashPassword);
		return password;
	}

}
